﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebSite.Web.Controllers
{
    public class FileController : Controller
    {

        public ActionResult Upload(HttpPostedFileBase imgFile, string dir, string localUrl)
        {

            //string aspxUrl =  Request.Path.Substring(0, Request.Path.LastIndexOf("/") + 1);

            ////文件保存目录路径
            //string savePath = "/attached/";

            ////文件保存目录URL
            //string saveUrl = "/attached/";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");



            //HttpPostedFile imgFile = Request.Files["imgFile"];
            if (imgFile == null)
            {
                return RedirectToAction("Error", new { message = "请选择文件" });

            }
            string baseDir = "/Upload/";
            string dirPath = Server.MapPath(baseDir);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
                //return RedirectToAction("Error", new { message = "上传目录不存在" });
            }

            if (string.IsNullOrEmpty(dir))
            {
                dir = "image";
            }
            if (!extTable.ContainsKey(dir))
            {
                return RedirectToAction("Error", new { message = "不支持的文件类型" });
            }

            string fileName = imgFile.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            //最大文件大小
            int maxSize = 10240000;
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return RedirectToAction("Error", new { message = "文件大小超过限制（10M）" });
            }

            if (string.IsNullOrEmpty(fileExt)
                || Array.IndexOf(((string)extTable[dir]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return RedirectToAction("Error", new { message = "上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dir]) + "格式。" });
            }

            //创建文件夹
            dirPath += dir + "/";
            //saveUrl += dir + "/";
            //if (!Directory.Exists(dirPath))
            //{
            //    Directory.CreateDirectory(dirPath);
            //}
            string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            //saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string newFileName = Guid.NewGuid().ToString() + fileExt;
            string filePath = dirPath + newFileName;

            imgFile.SaveAs(filePath);

            string fileUrl = baseDir + dir + "/" + ymd + "/" + newFileName;

            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            return Json(hash, "text/html; charset=UTF-8;", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Error(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            return Json(hash, "text/html; charset=UTF-8;", JsonRequestBehavior.AllowGet);
        }

    }
}
